package com.wechat.core.handler;


import com.netflix.client.ClientException;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.wechat.config.prperties.WxPayProperties;
import com.wechat.core.bean.Result;
import com.wechat.core.constant.enums.support.RStatus;
import com.wechat.core.exception.NotLoginException;
import com.wechat.core.exception.ServiceException;
import com.wechat.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 全局的的异常拦截器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    /**
     * 全局异常.
     *
     * @param e the e
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result exception(Exception e) {
        String profile = SpringUtil.getActiveProfile();
        log.error("内部异常：{}", e.getMessage(),e);
        if (!"dev".equals(profile)) {
            log.error("内部异常：{}", e.getMessage(),e);
        }
        if( e instanceof HystrixRuntimeException){
            Throwable cause = e.getCause();
            if(cause != null){
                if(cause instanceof ClientException){
                    return new Result<>(RStatus.FAIL,"系统升级中，请稍后重试");
                }
                if(cause instanceof TimeoutException){
                    return new Result<>(RStatus.FAIL,"系统超时，请重试");
                }
            }
            return new Result<>(RStatus.FAIL,"系统升级中，请稍后重试");
        }
        if(e instanceof ClientException || e instanceof HystrixBadRequestException){
            return new Result<>(RStatus.FAIL,"系统升级中，请稍后重试");
        }
        return new Result<>(RStatus.FAIL,"系统错误，请联系管理员");
    }

    /**
     * 业务异常.
     *
     * @param e the e
     * @return Result
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result serviceException(ServiceException e) {
        log.error("业务异常：{}", e.getMessage());
        return new Result<>(e);
    }

    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result notLoginException(NotLoginException e) {
        Map<String,String> map=new HashMap<>();
        HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sessionId=request.getSession().getId();
        if(redisTemplate.hasKey("S-ID:"+sessionId)){
            return new Result<>(RStatus.SUCCESS,"重复登录请求", map);
        }
        redisTemplate.opsForValue().set("S-ID:"+sessionId, "1", 5);
        System.out.println(request.getSession().getId()+":notlogin");
        String referer=request.getHeader("Referer");
        String redirectUrl=("http://"+wxPayProperties.getDomain()+"/whq/wechat/user/wechatLogin");
        String gotoUrl=String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s",
                wxPayProperties.getAppId(), redirectUrl, "snsapi_userinfo", "");
        map.put("url",gotoUrl);
        map.put("token","");
        return new Result<>(RStatus.NO_LOGIN,"未登录", map);
    }
}
